<template>
  <div class="box">
    <myDivider :name="scene == 'add' ? '添加巡查类别' : scene == 'update' ? '修改巡查类别' : '巡查类别详情'"></myDivider>
    <el-page-header @back="$router.go(-1)"></el-page-header>
    <!-- 步骤条 -->
    <div class="stepStyle">
      <div class="stepElStyle" @click="stepClick(1)" :class="activeStep == 1 ? 'active' : ''">
        <div>
          <span>1</span>
        </div>
        <span>巡查类别</span>
      </div>
      <div style="width: 211px;height: 2px;background-color: #4095e5;margin-top: 15px;"></div>
      <div class="stepElStyle" @click="stepClick(2)" :class="activeStep == 2 ? 'active' : ''">
        <div>
          <span>2</span>
        </div>
        <span>巡查内容</span>
      </div>
    </div>


    <!-- 步骤一 -->
    <div style="margin-top: 50px;" v-show="activeStep == 1">
      <el-form :model="typeForm" :rules="typeFormRules" ref="typeForm" label-width="200px">
        <el-form-item label="巡查类别名称：" prop="categoryName">
          <el-input :disabled="scene == 'detail'" style="width: 400px;" v-model="typeForm.categoryName" clearable
            placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="有效扫码距离配置：">
          距离扫码点
          <el-input @blur="effectiveDistanceBlur"  :disabled="scene == 'detail'" style="width: 150px;" v-model="typeForm.effectiveDistance"
            type="number" @input="typeForm.effectiveDistance = typeForm.effectiveDistance.replace(/\D/g, '');"
            oninput="if(value.length > 5) value=value.slice(0, 5)"></el-input>
          米，可扫码填写内容
          <el-tooltip class="item" effect="dark" content="不填写时，不限距离" placement="top-start">
            <i style="color: #4095e5;cursor: pointer;" class="el-icon-warning-outline"></i>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>

    <!-- 步骤二 -->
    <div style="margin-top: 50px;margin-left: 70px;" v-show="activeStep == 2">
      <div>
        <span>获取扫码位置：</span>
        <el-switch :disabled="scene == 'detail' || locationDisabled" v-model="location" active-color="#2a87ff" inactive-color="#909399">
        </el-switch>
      </div>
      <el-card shadow="never" v-for="item, i in mainForm" :key="i" style="margin-top: 20px;width: 500px;">
        <div slot="header" class="clearfix">
          <span>字段{{ i + 1 }}</span>
          <el-button v-if="mainForm.length > 1 && scene != 'detail'" @click="deleteCard(i)"
            style="float: right; padding: 3px 0;color:red" type="text">删除</el-button>
        </div>
        <el-form :model="item" ref="mainForms" label-width="100px" :rules="mainRules">
          <el-form-item label="填写类型：">
            <template>
              <el-radio @change="radioChange('image', i)" :disabled="scene == 'detail'" v-model="item.type"
                label="image">图片</el-radio>
              <el-radio @change="radioChange('text', i)" :disabled="scene == 'detail'" v-model="item.type"
                label="text">文本</el-radio>
              <el-radio @change="radioChange('radio', i)" :disabled="scene == 'detail'" v-model="item.type"
                label="radio">单选</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="是否必填项：">
            <template>
              <el-radio :disabled="scene == 'detail'" v-model="item.required" label="1">是</el-radio>
              <el-radio :disabled="scene == 'detail'" v-model="item.required" label="0">否</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="字段名称：" prop="title">
            <el-input :disabled="scene == 'detail'" style="width: 250px;" v-model="item.title"
              placeholder="请输入字段名称"></el-input>
          </el-form-item>
          <el-form-item label="单选内容：" prop="radioOptionString" v-if="item.type == 'radio'">
            <el-input :disabled="scene == 'detail'" style="width: 250px;" type="textarea" :rows="4" placeholder="一行一个内容"
              v-model="item.radioOptionString">
            </el-input>
          </el-form-item>
        </el-form>
      </el-card>

      <el-button type="success" style="margin-top: 20px;" @click="addCard" v-if="scene != 'detail'">添加字段</el-button>
    </div>


    <!-- 底部按钮 -->
    <div class="footer" v-if="scene != 'detail'">
      <div>
        <el-button style="width: 100px;" type="info" @click="cancellation">取消</el-button>
        <el-button style="width: 100px;" type="primary" @click="save">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    var validator1 = (rule, value, callback) => {
      // value 验重
      //对服务器验重....
      //  对目前起的名称验重
      let a = 0
      this.mainForm.forEach(el => {
        if (el.title == value) {
          a++
        }
      })
      if (a > 1) {
        callback(new Error('名称重复'));
      }
      callback()
    }
    var validator2 = (rule, value, callback) => {
      let arr = value.split('\n')
      arr.forEach(el => {
        if (!el) {
          callback(new Error('有空值'))
        }
      })
      function hasDuplicates(array) {
        return new Set(array).size !== array.length;
      }
      if (hasDuplicates(arr)) {
        callback(new Error('有重复的选项'))
      } else {
        callback()
      }
    }
    return {
      scene: '',
      activeStep: 1,
      // 步骤1 =============
      id: null,
      typeForm: {},
      typeFormRules: {
        categoryName: [{ required: true, message: '请输入巡查类别名称', trigger: 'blur' },],
      },
      //============= 步骤1 

      // 步骤二 =======================
      locationDisabled:false,
      mainForm: [{ type: 'image', required: '1', title: '', value: [] }],
      mainRules: {
        title: [{ required: true, message: '请输入字段名称', trigger: 'blur' },
        { validator: validator1, trigger: 'blur' }
        ],
        radioOptionString: [{ required: true, message: '请输入单选内容', trigger: 'blur' },
        { validator: validator2, trigger: 'blur' }
        ],
      },
      location: true,
      // =======================步骤二 
      logOnUser: {},

    }
  },
  async activated() {
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.scene = this.$route.query.scene
    this.activeStep = 1
    if (this.scene == 'add') {
      this.id = null

      this.$set(this.typeForm, 'categoryName', '')
      this.$set(this.typeForm, 'effectiveDistance', '')
      this.location = true
      this.mainForm = [{ type: 'image', required: '1', title: '请上传图片', value: '' }]
    }
    if (this.scene == 'detail' || this.scene == 'update') {
      let res = await this.$api.patrol.myPatrolCategoryDetail(this.$route.query.id)
      if (res.code == 200) {
        console.log(res, 'qwdqwdqw');
        this.id = res.data.id
        this.$set(this.typeForm, 'categoryName', res.data.categoryName)
        this.$set(this.typeForm, 'effectiveDistance', res.data.effectiveDistance)
        // 如果有巡查内容就显示
        if (res.data.codeContent) {
          let obj = JSON.parse(res.data.codeContent)
          console.log(obj.content, 'obj.content')
          obj.content.forEach(el => {
            if (el.type == 'radio') {
              el.radioOptionString = el.radioOption.join('\n')
            }
          })
          this.mainForm = obj.content
          this.location = obj.location == 1 ? true : false
        } else {
          this.location = true
          this.mainForm = [{ type: 'image', required: '1', title: '请上传图片', value: [] }]
        }

      } else {
        this.$message.error(res.message)
      }

    }


    this.$nextTick(() => {
      this.$refs.typeForm.clearValidate()
    })

  },
  methods: {
    effectiveDistanceBlur(){
      if(this.typeForm.effectiveDistance){
        this.location = true
        this.locationDisabled = true
      }else{
        this.locationDisabled = false
      }
    },
    radioChange(name, i) {
      switch (name) {
        case 'image':
          this.mainForm[i].title = '请上传图片'
          break
        case 'text':
          this.mainForm[i].title = '请输入文字'
          break
        case 'radio':
          this.mainForm[i].title = '请选择选项'
          break
      }
    },

    addCard() {
      this.mainForm.push({ type: 'image', required: '1', title: '请上传图片', value: [] })
    },
    deleteCard(index) {
      this.$confirm('是否删除该字段?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.mainForm.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {

      });

    },
    cancellation() { //底部取消按钮
      this.$confirm('取消后内容不保存，确定取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {

      });
    },
    save() {
      switch (this.activeStep) {
        case 1: //巡查类别————下一步
          this.$refs['typeForm'].validate((valid) => {
            if (valid) {
              if (!this.id) { //如果不存在，那么说明需要先添加类别

                this.$confirm('是否新增该巡查类别?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(async () => {
                  let res = await this.$api.patrol.myPatrolCategoryInsert({
                    "categoryName": this.typeForm.categoryName, //巡查类别名称 必填
                    "effectiveDistance": this.typeForm.effectiveDistance, //有效距离，单位米
                    "codeContent": "", //扫码内容，添加类别时先空着
                    "unitType": this.logOnUser.unitType, //和登录人一致
                    "unitId": this.logOnUser.unitId  //和登录人一致
                  })
                  if (res.code == 200) {
                    this.id = res.data
                    this.activeStep = 2
                  } else {
                    this.$message.error(res.message)
                  }

                }).catch(() => {

                });
              } else {  //如果存在，直接打开步骤二
                this.$confirm('是否修改该巡查类别?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(async () => {
                  let res = await this.$api.patrol.myPatrolCategoryUpdate({
                    id: this.id,
                    "categoryName": this.typeForm.categoryName, //巡查类别名称 必填
                    "effectiveDistance": this.typeForm.effectiveDistance, //有效距离，单位米
                    "codeContent": "", //扫码内容，添加类别时先空着
                  })
                  if (res.code == 200) {
                    this.activeStep = 2
                  } else {
                    this.$message.error(res.message)
                  }
                }).catch(() => {

                });
              }

            } else {

              return false;
            }
          });

          break
        case 2: //巡查内容————保存
          let qualifiedNum = 0
          this.mainForm.forEach((el, i) => {
            this.$refs['mainForms'][i].validate((valid) => {
              if (valid) {
                qualifiedNum++
              } else {
                return false;
              }
            });
          })
          if (qualifiedNum == this.mainForm.length) { //验证通过
            if (!this.id) {
              this.$message.error('请先添加巡查类别')
              return
            }

            this.mainForm.forEach((el, i) => {
              if (el.type == 'image') {
                el.value = []
              }
              if (el.type == 'text') {
                el.value = ''
              }
              if (el.type == 'radio') {
                el.radioOption = el.radioOptionString.split('\n')
                el.value = ''
              }
              el.sort = i + 1
            })
            let obj = {
              location: this.location ? 1 : 0, //暂时设定 1获取扫码位置，0不获取
              content: this.mainForm
            }
            let sceneName = this.scene == 'add' ? '新增' : '修改'
            this.$confirm(`是否${sceneName}`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let res = await this.$api.patrol.myPatrolCategoryUpdate({
                "id": this.id, //类别id
                "categoryName": this.typeForm.categoryName, //巡查类别名称
                "effectiveDistance": this.typeForm.effectiveDistance, //有效距离，单位厘米
                "codeContent": JSON.stringify(obj),
              })
              if (res.code == 200) {
                this.$message({
                  message: sceneName + '成功',
                  type: 'success'
                });
                this.$router.go(-1)
              } else {
                this.$message.error(res.message)
              }

            }).catch(() => {

            });
          }
          break
      }
    },
    stepClick(e) {
      this.activeStep = e
      return
      switch (e) {
        case 1:
          this.activeStep = e
          break;
        case 2: //如果点击的是第二步，那么闲判断第一步是否填写完毕，再转到第二步
          this.$refs['typeForm'].validate((valid) => {
            if (valid) {
              if (!this.id) { //如果不存在，那么说明需要先添加类别

                this.$confirm('是否新增该巡查类别?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  console.log('添加类别');
                  this.id = 1
                  this.activeStep = 2
                }).catch(() => {

                });
              } else {  //如果存在，直接打开步骤二
                this.activeStep = 2
              }
            } else {
              return false;
            }
          });
          break;
      }

    }
  }
} 
</script>






<style lang="less" scoped>
.stepStyle {
  display: flex;
  justify-content: space-between;
  width: 433px;
  margin: auto;

  .stepElStyle {
    cursor: pointer;
    width: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;

    >div {
      width: 30px;
      height: 30px;
      border-radius: 100px;
      // background-color: #4095e5;
      border: 1px solid black;
      display: flex;
      justify-content: center;
      align-items: center;

      >span {
        color: rgb(0, 0, 0);

      }
    }

    >span {
      margin-top: 5px;
    }

    &.active {
      >div {

        background-color: #4095e5;
        border: 1px solid #4095e5;

        >span {
          color: rgb(255, 255, 255);

        }
      }
    }
  }
}

.footer {
  position: fixed;
  bottom: 10px;
  left: 50%;

}
</style>